# -*- coding: utf-8 -*-


import numpy as np
from mako.template import Template
from metlib.data.misc import *
from metlib.datetime import *
try:
    import utm
except ImportError:
    pass


wws_head_template = Template(
    """version            : 43
site name          : ${site_name}
measurement period : ${begdt} - ${enddt}
site position      : ${'%.1f' % grid_x} ${'%.1f' % grid_y}
coordinate system  : 3
measurement height : ${level}
number of sectors  : ${wdbinnum}
number of bins     : ${wsbinnum}
total records      : ${wdbinnum * wsbinnum}

      ${'   '.join(['%d' % i for i in range(1, wdbinnum+1)])}
      ${'   '.join(['%.6f' % v for v in wddist])}
""")


def to_wws(data, dest, float_format='%.6f', encoding='utf-8'):
    c = {}  # context dict

    info = data['info']
    lon = info.get('grid_lon', 0)
    lat = info.get('grid_lat', 0)
    dataset = info.get('dataset')

    grid = 'unknown'
    for name in ['grid', 'jy_ix', 'latlon', 'lonlat']:
        if name in info:
            grid = info[name]
            break

    c['site_name'] = '-'.join([dataset, grid])
    # utm from_latlon return form (EASTING, NORTHING, ZONE NUMBER, ZONE LETTER)
    try:
        east, north, _, _ = utm.from_latlon(lat, lon)
    except Exception:
        east, north = lat, lon
    c['grid_x'] = east
    c['grid_y'] = north

    dt_format = '%Y/%m/%d %H:%M:%S'
    try:
        begdt = T(info.get('begdt'))
        enddt = T(info.get('enddt'))
    except Exception:
        begdt = T(19700101)
        enddt = T(19700101)
        time_str = None
        for name in ['time', 'year', 'date']:
            if name in info:
                time_str = info[name]
                break
        if time_str:
            if ':' in time_str:
                begdt, enddt, tdelta = parse_slice_str(time_str, default_step='1h')
                begdt = T(begdt)
                enddt = T(enddt)
            elif len(time_str) == 4:  # year
                begdt = T(time_str + '0101')
                enddt = begdt + TD('1Y')
    c['begdt'] = begdt.strftime(dt_format)
    c['enddt'] = enddt.strftime(dt_format)

    c['level'] = info.get('level', '-999')

    values = np.array(data['data']['values']) / 1000.0
    c['wddist'] = np.nansum(values, axis=0)
    c['wsbinnum'] = values.shape[0]
    c['wdbinnum'] = values.shape[1]

    wsbins = data['data']['wsbins']

    contents = wws_head_template.render(**c)
    with open(dest, 'w') as outf:
        outf.write(contents)
        last_ws = 0
        for i, (ws, v_row) in enumerate(zip(wsbins, values)):
            # TODO: more complex ws format
            ws = int(ws)
            ws_str = '%.1f - %.1f' % (last_ws, ws)
            outf.write('%d   %s' % (i+1, ws_str))
            for v in v_row:
                outf.write('   %.6f' % v)
            outf.write('\n')
            last_ws = ws

    return dest
